package com.hzz.task;

import com.alibaba.fastjson.JSONObject;
import com.hzz.dao.dsync.IDSyncDao;
import com.hzz.dao.eybase.IEyBaseImportDao;
import com.hzz.dao.patrol.IPatrolTaskDao;
import com.hzz.dao.report.IReportEventDao;
import com.hzz.dao.user.IUserDao;
import com.hzz.entity.dsync.DSync;
import com.hzz.entity.patrol.PatrolTask;
import com.hzz.entity.report.ReportEvent;
import com.hzz.framework.Response;
import com.hzz.framework.scheduling.TriggerTask;
import com.hzz.framework.util.CommonConstant;
import com.hzz.framework.util.DateUtil;
import com.hzz.framework.util.ValidatorUtil;
import com.hzz.service.dsync.BaseDSync;
import com.hzz.service.dsync.ErReportTaskDSync;
import com.hzz.service.dsync.EyBaseTaskDSync;
import com.hzz.service.dsync.PatrolTaskDSync;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.List;

@Component
@Slf4j
public class DSyncTask {
    @Autowired
    BaseDSync baseDSync;
    @Autowired
    IDSyncDao dsyncDao;
    @Autowired
    PatrolTaskDSync patrolTaskDSync;
    //    @Autowired
//    IDSyncExistDao dsyncExistDao;
    @Autowired
    IPatrolTaskDao patrolTaskDao;
    @Autowired
    IReportEventDao reportEventDao;
    @Autowired
    EyBaseTaskDSync eyBaseTaskDSync;
    @Autowired
    ErReportTaskDSync erReportTaskDSync;
    @Autowired
    IEyBaseImportDao eyBaseImportDao;
    @Autowired
    IUserDao userDao;

    @Component
    @Data
    public class TaskRecordDSyncScheduleTask extends TriggerTask {
        @Value("${dsync.eySubmit.cron}")
        @Override
        public void setCron(String cron) {
            super.setCron(cron);
        }

        private Runnable task = () -> {
            log.info("Current time： {}", LocalDateTime.now());
            TaskRecordDSync();
        };
    }

    public Response TaskRecordDSync() {
        DSync dSync = new DSync();
        Calendar calendar = Calendar.getInstance();
        dSync.setDateEnd(DateUtil.getDateStr(calendar.getTime(), "yyyy-MM-dd"));
        calendar.add(Calendar.DATE, -1);
        dSync.setDateBegin(DateUtil.getDateStr(calendar.getTime(), "yyyy-MM-dd"));
        return TaskRecordDSync(dSync);
    }

    public Response TaskRecordDSync(DSync dSync) {
        log.info("TaskRecordDSync..进入..");
        Response result = new Response();
        int data200 = 0;
        int data500 = 0;
        try {
            if (!baseDSync.getSyncEnabled()) {
                return Response.error("已停用同步功能");
            }
            synchronized (this) {
                PatrolTask dSyncEntity = new PatrolTask();
                dSyncEntity.setTaskStatus(CommonConstant.TASK_STATUS_巡查任务_已巡查);
                dSyncEntity.setIsDSync(1);
                dSyncEntity.setDateBegin(dSync.getDateBegin());
                dSyncEntity.setDateEnd(dSync.getDateEnd());
                List<PatrolTask> dSyncs = (List<PatrolTask>) patrolTaskDao.findDataIsList(dSyncEntity);
                if (dSyncs != null && dSyncs.size() > 0) {
                    for (PatrolTask patrolTask : dSyncs) {
                        if (ValidatorUtil.isEmpty(patrolTask.getExecutorAccount())/* || dsyncExistDao.isDataFinishById(StrUtil.asString(patrolTask.getId())) > 0*/) {
                            continue;
                        }
                        Response theResponse = null;
                        try {
                            theResponse = patrolTaskDSync.patrolTaskRecord(patrolTask);
                        } catch (Exception e) {
                            theResponse = Response.error(500);
                            log.error("同步失败!", e);
                        } finally {
                            log.warn("TaskRecord同步结果:{}", theResponse);
                            if (theResponse.code == CommonConstant.TASK_STATUS_基础数据_成功拉取) {
                                data200++;
                            } else {
                                data500++;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("TaskRecordDSync..异常..", e);
            result = Response.error(500, "异常." + e.getMessage());
        } finally {
            log.info("TaskRecordDSync..结束..");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", data200);
        jsonObject.put("error", data500);
        result.data = jsonObject;
        return result;
    }

    @Component
    @Data
    public class TaskEventDSyncScheduleTask extends TriggerTask {
        @Value("${dsync.eySubmit.cron}")
        @Override
        public void setCron(String cron) {
            super.setCron(cron);
        }

        private Runnable task = () -> {
            log.info("Current time： {}", LocalDateTime.now());
            TaskEventDSync();
        };
    }

    public Response TaskEventDSync() {
        DSync dSync = new DSync();
        Calendar calendar = Calendar.getInstance();
        dSync.setDateEnd(DateUtil.getDateStr(calendar.getTime(), "yyyy-MM-dd"));
        calendar.add(Calendar.DATE, -1);
        dSync.setDateBegin(DateUtil.getDateStr(calendar.getTime(), "yyyy-MM-dd"));
        return TaskEventDSync(dSync);
    }

    public Response TaskEventDSync(DSync dSync) {
        log.info("TaskEventDSync..进入..");
        Response result = new Response();
        int data200 = 0;
        int data500 = 0;
        try {
            if (!baseDSync.getSyncEnabled()) {
                return Response.error("已停用同步功能");
            }
            synchronized (this) {
                ReportEvent dSyncEntity = new ReportEvent();
                dSyncEntity.setReportingType(0);
                dSyncEntity.setIsDSync(1);
                dSyncEntity.setDateBegin(dSync.getDateBegin());
                dSyncEntity.setDateEnd(dSync.getDateEnd());
                List<ReportEvent> dSyncs = (List<ReportEvent>) reportEventDao.findDataIsList(dSyncEntity);
                if (dSyncs != null && dSyncs.size() > 0) {
                    for (ReportEvent reportEvent : dSyncs) {
                        if (reportEvent.getPatrolTaskId() == null/* || dsyncExistDao.isDataFinishById(StrUtil.asString(reportEvent.getId())) > 0*/) {
                            continue;
                        }
                        Response theResponse = null;
                        try {
                            theResponse = patrolTaskDSync.patrolTaskEvent(reportEvent);
                        } catch (Exception e) {
                            theResponse = Response.error(500);
                            log.error("同步失败!", e);
                        } finally {
                            log.warn("TaskEvent同步结果:{}", theResponse);
                            if (theResponse.code == CommonConstant.TASK_STATUS_基础数据_成功拉取) {
                                data200++;
                            } else {
                                data500++;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("TaskEventDSync..异常..", e);
        } finally {
            log.info("TaskEventDSync..结束..");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", data200);
        jsonObject.put("error", data500);
        result.data = jsonObject;
        return result;
    }

    @Component
    @Data
    public class DsyncEyBaseTaskDSyncScheduleTask extends TriggerTask {

        @Value("${dsync.eyBase.cron}")
        @Override
        public void setCron(String cron) {
            super.setCron(cron);
        }

        private Runnable task = () -> {
            log.info("Current time： {}", LocalDateTime.now());
            dsyncEyBaseTaskDSync();
        };
    }

    public void dsyncEyBaseTaskDSync() {
        log.info("dsyncEyBaseTaskDSync..进入..");
        try {
            if (!baseDSync.getSyncEnabled()) {
                log.error("已停用同步功能");
                return;
            }
            synchronized (this) {
                // 行政区划
                eyBaseTaskDSync.dsyncEyBaseRetrieveRegion();
                // 河长
                eyBaseTaskDSync.dsyncEyBaseRetrieveGm();
                // 河流
                eyBaseTaskDSync.dsyncEyBaseRetrieveRivers();
                // 河段
                eyBaseTaskDSync.dsyncEyBaseRetrieveReachPage();
                // 渠道
                eyBaseTaskDSync.dsyncEyBaseRetrieveChn();
                // 渠段
                eyBaseTaskDSync.dsyncEyBaseRetrieveChnSlice();
                // 河段和河长关系
                eyBaseTaskDSync.dsyncEyBaseRetrieveGmHydl();
                // 渠道和河长关系
                eyBaseTaskDSync.dsyncEyBaseRetrieveChnGm();
                // 水库
                eyBaseTaskDSync.dsyncEyBaseReservoirs();
                // 库片
                eyBaseTaskDSync.dsyncEyBaseReservoirsSlice();
                // 水库和河长关系
                eyBaseTaskDSync.dsyncEyBaseReservoirsGm();
            }
        } catch (Exception e) {
            log.error("dsyncEyBaseTaskDSync..异常..", e);
        } finally {
            log.info("dsyncEyBaseTaskDSync..结束..");
        }
    }

    @Component
    @Data
    public class DsyncEyBaseImportScheduleTask extends TriggerTask {

        @Value("${dsync.eyBase.cron-import}")
        @Override
        public void setCron(String cron) {
            super.setCron(cron);
        }

        private Runnable task = () -> {
            log.info("Current time： {}", LocalDateTime.now());
            dsyncEyBaseImport();
        };
    }

    public void dsyncEyBaseImport() {
        log.info("dsyncEyBaseImport..进入..");
        try {
            if (!baseDSync.getSyncEnabled()) {
                log.error("已停用同步功能");
                return;
            }
            synchronized (this) {
                try {
                    eyBaseImportDao.importUser(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    userDao.updateInvalidUser();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    eyBaseImportDao.importUserRole(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    eyBaseImportDao.deleteType1(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    eyBaseImportDao.importType1(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    eyBaseImportDao.deleteType2(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    eyBaseImportDao.importType2(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    eyBaseImportDao.deleteType3(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    eyBaseImportDao.importType3(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            log.error("dsyncEyBaseImport..异常..", e);
        } finally {
            log.info("dsyncEyBaseImport..结束..");
        }
    }

    @Component
    @Data
    public class DsyncEyBaseTccDSyncScheduleTask extends TriggerTask {

        @Value("${dsync.eyBase.cron-tcc}")
        @Override
        public void setCron(String cron) {
            super.setCron(cron);
        }

        private Runnable task = () -> {
            log.info("Current time： {}", LocalDateTime.now());
            dsyncEyBaseTccDSync();
        };
    }

    public void dsyncEyBaseTccDSync() {
        log.info("dsyncEyBaseTccDSync..进入..");
        try {
            if (!baseDSync.getSyncEnabled()) {
                log.error("已停用同步功能");
                return;
            }
            synchronized (this) {
                DSync dSyncEntity = new DSync();
                List<DSync> dSyncs = (List<DSync>) dsyncDao.findDataIsList(dSyncEntity);
                if (dSyncs != null && dSyncs.size() > 0) {
                    for (DSync dSync : dSyncs) {
                        Response response = new Response(0);
                        try {
                            String apiUrl = dSync.getApiurl();
                            String djson = dSync.getDjson();
                            response = baseDSync.syncPost(dSync.getId(), djson, apiUrl);
                            switch (dSync.getType()) {
                                case CommonConstant.TASK_拉取_EY_河长: {
                                    eyBaseTaskDSync.dsyncEyBaseRetrieveGm(apiUrl, djson, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_EY_河流: {
                                    eyBaseTaskDSync.dsyncEyBaseRetrieveRivers(apiUrl, djson, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_EY_河段VS河长: {
                                    eyBaseTaskDSync.dsyncEyBaseRetrieveGmHydl(apiUrl, djson, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_EY_河段: {
                                    eyBaseTaskDSync.dsyncEyBaseRetrieveReachPage(apiUrl, djson, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_EY_行政区划: {
                                    eyBaseTaskDSync.dsyncEyBaseRetrieveRegion(apiUrl, djson, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_EY_渠道: {
                                    eyBaseTaskDSync.dsyncEyBaseRetrieveChn(apiUrl, djson, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_EY_渠段: {
                                    eyBaseTaskDSync.dsyncEyBaseRetrieveChnSlice(apiUrl, djson, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_EY_渠道VS河长: {
                                    eyBaseTaskDSync.dsyncEyBaseRetrieveChnGm(apiUrl, djson, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_EY_水库: {
                                    eyBaseTaskDSync.dsyncEyBaseReservoirs(apiUrl, djson, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_EY_库片: {
                                    eyBaseTaskDSync.dsyncEyBaseReservoirsSlice(apiUrl, djson, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_EY_水库VS河长: {
                                    eyBaseTaskDSync.dsyncEyBaseReservoirsGm(apiUrl, djson, response);
                                    break;
                                }
                                default: {
                                    continue;
                                }
                            }
                            if (response != null && response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取) {
                                Thread.sleep(15 * 1000);
                            }
                        } catch (Exception e) {
                            response = Response.error(500);
                            log.error("同步失败!", e);
                        } finally {
                            if (response != null && response.code == CommonConstant.TASK_STATUS_基础数据_成功拉取) {
                                eyBaseTaskDSync.logDSyncDel(dSync.getId());
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("dsyncPatrolTaskDSync..异常..", e);
        } finally {
            log.info("dsyncPatrolTaskDSync..结束..");
        }
    }

    @Component
    @Data
    public class DsyncErReportTccDSyncScheduleTask extends TriggerTask {

        @Value("${dsync.erReport.cron-tcc}")
        @Override
        public void setCron(String cron) {
            super.setCron(cron);
        }

        private Runnable task = () -> {
            log.info("Current time： {}", LocalDateTime.now());
            dsyncErReportTccDSync();
        };
    }

    public void dsyncErReportTccDSync() {
        log.info("dsyncErReportTccDSync..进入..");
        try {
            if (!erReportTaskDSync.getSyncEnabled()) {
                log.error("已停用同步功能");
                return;
            }
            synchronized (this) {
                DSync dSyncEntity = new DSync();
                List<DSync> dSyncs = (List<DSync>) dsyncDao.findDataIsList(dSyncEntity);
                if (dSyncs != null && dSyncs.size() > 0) {
                    for (DSync dSync : dSyncs) {
                        Response response = new Response(0);
                        try {
                            String apiUrl = dSync.getDjson();
                            response = baseDSync.syncGet(dSync.getId(), dSync.getDjson());
                            switch (dSync.getType()) {
                                case CommonConstant.TASK_拉取_ER_旬报1: {
                                    erReportTaskDSync.xbOnePage(apiUrl, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_ER_旬报2: {
                                    erReportTaskDSync.xbTwoPage(apiUrl, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_ER_旬报3: {
                                    erReportTaskDSync.xbThreePage(apiUrl, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_ER_月小结报: {
                                    erReportTaskDSync.monthSummaryPage(apiUrl, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_ER_工作简报: {
                                    erReportTaskDSync.briefPage(apiUrl, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_ER_双月报: {
                                    erReportTaskDSync.xdOnePage(apiUrl, response);
                                    break;
                                }
                                case CommonConstant.TASK_拉取_ER_年报: {
                                    erReportTaskDSync.xyOnePage(apiUrl, response);
                                    break;
                                }
                                default: {
                                    continue;
                                }
                            }
                            if (response != null && response.code != CommonConstant.TASK_STATUS_基础数据_成功拉取) {
                                Thread.sleep(15 * 1000);
                            }
                        } catch (Exception e) {
                            response = Response.error(500);
                            log.error("同步失败!", e);
                        } finally {
                            if (response != null && response.code == CommonConstant.TASK_STATUS_基础数据_成功拉取) {
                                erReportTaskDSync.logDSyncDel(dSync.getId());
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("dsyncErReportTccDSync..异常..", e);
        } finally {
            log.info("dsyncErReportTccDSync..结束..");
        }
    }

    @Component
    @Data
    public class DsyncErReportTaskDSyncScheduleTask extends TriggerTask {

        @Value("${dsync.erReport.cron}")
        @Override
        public void setCron(String cron) {
            super.setCron(cron);
        }

        private Runnable task = () -> {
            log.info("Current time： {}", LocalDateTime.now());
            dsyncErReportTaskDSync();
        };
    }

    public void dsyncErReportTaskDSync() {
        log.info("dsyncErReportTaskDSync..进入..");
        try {
            if (!erReportTaskDSync.getSyncEnabled()) {
                log.error("已停用同步功能");
                return;
            }
            synchronized (this) {
                // 拉取_ER_旬报1
                erReportTaskDSync.xbOnePage();
                // 拉取_ER_旬报2
                erReportTaskDSync.xbTwoPage();
                // 拉取_ER_旬报3
                erReportTaskDSync.xbThreePage();
                // 拉取_ER_月小结报
                erReportTaskDSync.monthSummaryPage();
                // 拉取_ER_工作简报
                erReportTaskDSync.briefPage();
                // 拉取_ER_双月报
                erReportTaskDSync.xdOnePage();
                // 拉取_ER_年报
                erReportTaskDSync.xyOnePage();
            }
        } catch (Exception e) {
            log.error("dsyncErReportTaskDSync..异常..", e);
        } finally {
            log.info("dsyncErReportTaskDSync..结束..");
        }
    }

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        System.out.println(DateUtil.getDateStr(calendar.getTime(), "yyyy-MM-dd 00:00:01"));
        calendar.add(Calendar.DATE, 2);
        System.out.println(DateUtil.getDateStr(calendar.getTime(), "yyyy-MM-dd 00:00:00"));
    }
}
